package com.party.web.web.controller.charge;

import com.google.common.collect.Lists;
import com.party.common.paging.Page;
import com.party.common.utils.StringUtils;
import com.party.core.model.BaseModel;
import com.party.core.model.charge.PackageMember;
import com.party.core.model.charge.ProductPackage;
import com.party.core.model.charge.ProductType;
import com.party.core.model.member.PackageCount;
import com.party.core.model.order.OrderForm;
import com.party.core.model.system.SysRole;
import com.party.core.model.system.TargetType;
import com.party.core.service.charge.IPackageMemberService;
import com.party.core.service.charge.IPackageService;
import com.party.core.service.member.IPackageCountService;
import com.party.web.biz.charge.PackageBizService;
import com.party.web.biz.order.OrderBizService;
import com.party.web.biz.pay.PayPcOrderBizService;
import com.party.web.utils.RealmUtils;
import com.party.web.web.dto.AjaxResult;
import com.party.web.web.dto.output.charge.PackagePrivilegeOutput;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import java.util.List;
import java.util.Map;

/**
 * 等级
 */
@Controller
@RequestMapping("/charge/package")
public class PackageController {
    @Autowired
    private IPackageService packageService;
    @Autowired
    private PackageBizService packageBizService;
    @Autowired
    private PayPcOrderBizService payPcOrderBizService;
    @Autowired
    private IPackageMemberService packageMemberService;
    @Autowired
    private IPackageCountService packageCountService;
    @Autowired
    private OrderBizService orderBizService;
    Logger logger = LoggerFactory.getLogger(getClass());

    /**
     * 等级套餐
     *
     * @return
     */
    @RequestMapping("packageList")
    public ModelAndView levelList() {
        ModelAndView mv = new ModelAndView("charge/packageList");
        ProductPackage productPackage = new ProductPackage();
        productPackage.setDelFlag(BaseModel.DEL_FLAG_NORMAL);
        productPackage.setType(ProductType.PACKAGE_TYPE.getCode());
        List<ProductPackage> productPackages = packageService.list(productPackage);
        mv.addObject("packages", productPackages);

        String memberId = RealmUtils.getCurrentUser().getId();
        List<SysRole> sysRoles = Lists.newArrayList();
        PackageMember packageMember = packageBizService.getPackageMember(memberId, sysRoles);
        mv.addObject("packageMember", packageMember);
        mv.addObject("sysRoles", sysRoles);

        List<PackagePrivilegeOutput> privileges = packageBizService.getPackagePrivilegeList(productPackages);
        mv.addObject("privileges", privileges);
        return mv;
    }

    /**
     * 套餐购买
     *
     * @param levelId 套餐id
     * @return
     */
    @Transactional
    @RequestMapping("{levelId}/buyOrder")
    public ModelAndView buyOrder(@PathVariable("levelId") String levelId) {
        ModelAndView mv = new ModelAndView("charge/buyOrder");
        ProductPackage productPackage = packageService.get(levelId);
        String msg = "订单支付完成，请重新登录体验新的增值服务";
        if (productPackage.getType().equals(3)) {
            msg = "订单支付完成";
        }
        mv.addObject("msg", msg);
        mv.addObject("level", productPackage);
        return mv;
    }

    /**
     * 模块列表
     *
     * @return
     */
    @RequestMapping("moduleList")
    public ModelAndView moduleList() {
        ModelAndView mv = new ModelAndView("charge/moduleList");
        ProductPackage productPackage = new ProductPackage();
        productPackage.setDelFlag(BaseModel.DEL_FLAG_NORMAL);
        productPackage.setType(ProductType.MODULE_TYPE.getCode());
        List<ProductPackage> productPackages = packageService.list(productPackage);
        mv.addObject("packages", productPackages);

        String memberId = RealmUtils.getCurrentUser().getId();
        List<PackageMember> packageMembers = packageBizService.getPackaeMemberModule(memberId);
        // List<PackageMember> packageMembers = packageMemberService.list(new PackageMember("", memberId));
        mv.addObject("packageMembers", packageMembers);
        return mv;
    }

    /**
     * 免费模块购买
     *
     * @param moduleId
     * @return
     */
    @ResponseBody
    @RequestMapping("buyFreeModule")
    public AjaxResult buyFreeModule(String moduleId) {
        if (StringUtils.isEmpty(moduleId)) {
            return AjaxResult.error("购买失败");
        }

        String memberId = RealmUtils.getCurrentUser().getId();
        try {
            payPcOrderBizService.freeUpdateBusiness(moduleId, memberId);
        } catch (Exception e) {
            logger.error("免费套餐购买异常", e);
        }
        return AjaxResult.success();
    }

    /**
     * 短信套餐列表
     *
     * @return
     */
    @RequestMapping("smsPackageList")
    public ModelAndView smsPackageList() {
        String memberId = RealmUtils.getCurrentUser().getId();
        ModelAndView mv = new ModelAndView("charge/smsPackageList");
        ProductPackage productPackage = new ProductPackage();
        productPackage.setDelFlag(BaseModel.DEL_FLAG_NORMAL);
        productPackage.setType(ProductType.SMS_PACKAGE_TYPE.getCode());
        List<ProductPackage> productPackages = packageService.list(productPackage);
        mv.addObject("packages", productPackages);
        List<PackageMember> packageMembers = packageBizService.getPackageMemberSms(memberId);
        mv.addObject("packageMembers", packageMembers);
        return mv;
    }

    /**
     * 短信套餐明细列表
     *
     * @return
     */
    @RequestMapping("packageMemberList")
    public ModelAndView packageMemberList(ProductPackage productPackage, Page page) {
        if (null == productPackage.getType()) {
            productPackage.setType(3);
        }
        int type = productPackage.getType();
        String memberId = RealmUtils.getCurrentUser().getId();
        ModelAndView mv = new ModelAndView("system/member/packageMemberList");
        PackageMember packageMember = new PackageMember();
        // List<ProductPackage> productPackages = packageService.list(productPackage);
        packageMember.setMemberId(memberId);
        page.setLimit(10);
        // List<PackageMember> packageMembers = packageMemberService.listPage(packageMember, page);
        PackageCount packageCount = packageCountService.getUnique(new PackageCount(memberId, TargetType.PUSH_SMS.getCode()));
        Map<String, Object> indexMap = orderBizService.memberIndexMap(false);
        List<PackageMember> pmList = packageMemberService.getPackageMemberByType(memberId, type, page);
        mv.addObject("pmList", pmList);
        mv.addObject("packageCount", packageCount);
        mv.addObject("page", page);
        mv.addObject("type", productPackage.getType());
        mv.addAllObjects(indexMap);
        return mv;
    }

    /**
     * 生成订单
     *
     * @param paymentWay 支付方式
     * @param packageId  套餐id
     * @return
     */
    @ResponseBody
    @RequestMapping("insertOrder")
    public AjaxResult insertOrder(Integer paymentWay, String packageId, Integer quantity) {
        if (paymentWay == null || StringUtils.isEmpty(packageId)) {
            return AjaxResult.error("信息不完整，无法购买");
        }
        try {
            OrderForm orderForm = packageBizService.buyOrder(paymentWay, packageId, quantity);
            return AjaxResult.success((Object) orderForm.getId());
        } catch (Exception e) {
            logger.error("生成订单异常", e);
        }
        return AjaxResult.error("订单生成失败");
    }

    /**
     * @param
     * @Author yifeng
     * @Description 续费页面
     * @Date 14:22 2019/2/28
     **/
    @RequestMapping("renewals")
    public ModelAndView renewals() {
        ModelAndView mv = new ModelAndView("charge/renewals");

//        List<PackageListOutput> packageList = Lists.newArrayList();
//
//        PackageListOutput package1 = new PackageListOutput();
//        package1.setLevel(1);
//        package1.setName("普通套餐");
//        package1.setDesc("签约1年，暂无优惠");
//        package1.setPrice(3000d);
//        package1.setYear(1);
//
//        PackageListOutput package2 = new PackageListOutput();
//        package2.setLevel(2);
//        package2.setName("会员套餐");
//        package2.setDesc("一次性签约2年，优惠1000元");
//        package2.setPrice(5000d);
//        package2.setYear(2);
//
//        PackageListOutput package3 = new PackageListOutput();
//        package3.setLevel(3);
//        package3.setName("VIP套餐");
//        package3.setDesc("一次性签约3年，优惠3000元");
//        package3.setPrice(6000d);
//        package3.setYear(3);
//
//        packageList.add(package1);
//        packageList.add(package2);
//        packageList.add(package3);
//        mv.addObject("packageList", packageList);
//
//        List<String> moduleList = Lists.newArrayList();
//        moduleList.add("活动管理");
//        moduleList.add("众筹管理");
//        moduleList.add("圈子管理");
//        moduleList.add("手机官网");
//        moduleList.add("运动打卡");
//        moduleList.add("行者相册");
//        moduleList.add("赛事成绩管理");
//        moduleList.add("人员信息收集分组");
//        moduleList.add("自定义信息收集");
//        moduleList.add("会员管理");
//        moduleList.add("消息管理");
//        moduleList.add("公众号管理");
//        moduleList.add("二维码生成");
//        moduleList.add("图片管理");
//        mv.addObject("moduleList", moduleList);

        return mv;
    }

    /**
     * 生成系统购买订单
     *
     * @param paymentWay 支付方式
     * @param packageMemberId  套餐id
     * @return
     */
    @ResponseBody
    @RequestMapping("systemBuy/insertOrder")
    public AjaxResult insertSystemBuyOrder(Integer paymentWay, String packageMemberId) {
        if (paymentWay == null || StringUtils.isEmpty(packageMemberId)) {
            return AjaxResult.error("信息不完整，无法购买");
        }
        try {
            OrderForm orderForm = packageBizService.systemBuyOrder(paymentWay, packageMemberId);
            return AjaxResult.success((Object) orderForm.getId());
        } catch (Exception e) {
            logger.error("生成订单异常", e);
        }
        return AjaxResult.error("订单生成失败");
    }
}
